package com.yjzx.util.service.pool;

import com.yjzx.util.service.pool.properties.AppThreadPoolProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(AppThreadPoolProperties.class)
public class AppThreadPoolConfiguration {
    @Primary
    @Bean
    public ThreadPoolExecutor
    corePool(AppThreadPoolProperties threadPoolProperties,
             @Value("${spring.application.name}") String applicationName) {
        return new ThreadPoolExecutor(
                //核心线程
                threadPoolProperties.getCorePoolSize(),
                //最大线程
                threadPoolProperties.getMaximumPoolSize(),
                //空闲非核心线程等待时间
                threadPoolProperties.getKeepAliveTime(),
                //等待时间单位
                TimeUnit.MILLISECONDS,
                //线程任务队列
                new LinkedBlockingQueue<>(threadPoolProperties.getWorkQueueSize()),
                //线程工厂
                new ThreadFactory() {
                    private int i;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(() -> {
                            r.run();
                        });
                        t.setName("[" + applicationName + "]-apppool-" + (i++));
                        return t;
                    }
                },
                //线程策略
                new ThreadPoolExecutor.CallerRunsPolicy());

    }
}
